<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/5
 * Time: 13:34
 */
namespace app\api\controller\followmanage;
use app\api\controller\common\ApiBase;
use Think\Db;
use app\api\model\Admin as AdminModel;

//展商控制器
class Company extends ApiBase
{
    protected $admin;
    protected $model = null;
    private $data = [
        'id' => '序号',
        'zs_name' => '展商名称',
        'zs_status' => '展商状态',
        'jbcz' => '基本操作',
        'ywy' => '业务员',
        'zw_number' => '展位号',
        'zw_type' => '展位类别',
        'zw_area' => '展位面积',
        'zp_type' => '展品类别',
        'source' => '来源',
        'lb' => '连报',
        'sale_jd' => '销售进度',
        'time' => '最后联络时间',
        'member_grade' => '会员等级',
        'member_id' => '会员编号',
        'zs_id' => '展商编号',
        'zs_type' => '展商类别',
    ];

    private $status_name =[
        '-1'=>'不参展',
        '-2'=>'退展展商',
        '0'=>'未联系',
        '1'=>'已联系',
        '2'=>'有意向',
        '3'=>'预定展商',
        '4'=>'签约展商',
        '5'=>'部分付款',
        '6'=>'全部付款',
    ];

    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('CompanyFollow');
    }
    /**
     *展商可筛选字段显示
     **/
    public function screenField(){
        $data = $this->data;
        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }
    /**
     * 展商列表
     * @param member_id,public_id,sale_id
     */
    public function companyList(){
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize = 10;
        $list_key = input('list_key');//需要返回的列
        $where['f.is_status'] = array('=',1);//退回公海的不显示
        $where['f.status'] = array('EGT',3);
        if(!empty($this->request->param('project_id'))){
            $where['p.project_id'] = $this->request->param('project_id');
        }
        if(!empty($this->request->param('exhibition_id'))){
            $where['p.exhibition_id'] = $this->request->param('exhibition_id');
        }
        $list = Db::name('company_follow')
            ->alias('f')
            ->field('f.*,a.realname,a.mobile')
            ->join('company_public p','f.public_id=p.id','left')
            ->join('admin a','f.member_id=a.id','left')
            ->where($where)
            ->order('a.id desc')
            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->select();
        $data =array();
        foreach ($list as $k =>$v){
            //获取映射表公司信息
            $company_public_company =  db('company_public_company')->where(['c_id'=>$v['company_id'],'public_id'=>$v['public_id']])->find();
            //最近联络时间
            $where1['follow_id'] = $v['id'];
            $where1['public_id'] = $v['public_id'];
            $where1['member_id'] = $this->admin['id'];
            $FollowLog = model('FollowLog')->where($where1)->order('time desc')->find();

            $data[$k]['id'] = $v['id'];//序号
            $data[$k]['zs_name'] = $company_public_company['zs_name'];//展商名称
            $data[$k]['zs_status'] = $v['status'];//展商状态
            $data[$k]['zs_status_name'] = $this->status_name[$v['status']];//展商状态名字
            $data[$k]['jbcz'] = 1;//基本操作
            $data[$k]['ywy'] = $v['realname'];//业务员
            $data[$k]['zw_number'] = '';//展位号
            $data[$k]['zw_type'] = '';//展位类别
            $data[$k]['zw_area'] = '';//展位面积
            $data[$k]['zp_type'] = '';//展品类别
            $data[$k]['source'] = $v['is_old'];//来源
            $data[$k]['lb'] = '';//连报
            $data[$k]['sale_jd'] = $v['status'];//销售进度
            $data[$k]['time'] = date('Y-m-d H:i:s',$FollowLog['time']);//最后联络时间
            $data[$k]['member_grade'] = '';//会员等级
            $data[$k]['member_id'] = '';//会员编号
            $data[$k]['zs_type'] = '';//展商类别
            unset($company_public_company);
            unset($FollowLog);
        }
        //如果不为空则返回指定列
        if(!empty($list_key)){
            $list_key = explode(',',input('list_key'));//需要返回的列
            $datas = [];
            foreach ($list_key as $value){
                $datas[] = array_column($data,$value,$value);
                if($value =='zs_status'){
                    $datas[] = array_column($data,'zs_status_name','zs_status_name');
                }
            }
        }else{
            $datas = $data;
        }
        unset($data);

        $total =  Db::name('company_follow')->alias('f')->join('company_public p','f.public_id=p.id','left')->where($where)->count();
//        //统计各个状态下的数量
        $status_count = $this->model->field("status,count('id') as sum")->where(['is_status'=>array('<>',-1)])->group('status')->select();
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$datas,'count'=>$total,'page'=>$total,' pagesize'=>$pagesize,'status_count'=>$status_count]]);
    }

    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $where['is_super'] = 0;
            if ($orgId != 0) {
                // $where['a.org_id'] = $orgId;
                $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_organization b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.org_name,a.create_time,a.update_time')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     * 获取当前管理员展会列表
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserExhib(){

        $where['merchants_manager'] = $this->admin['id'];
        $where['endtime'] = array('LT',date('Y-m-d',time()));
        $where['is_delete'] = 0;
        $data = db('exhibition')->field('title,id')->where($where)->select();

        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }

    /**
     * 私海列表
     * @param member_id,public_id,sale_id
     */
    public function followList(){
        $page = $this->request->param('page');
        $page = max(1,intval($page));
        $pagesize = input('pagesize');
        $pagesize = empty($pagesize)?10:$pagesize;//吗默认为10

        $list_key = input('list_key');//需要返回的列

        $where['f.is_status'] = array('<>',-1);//退回公海的不显示
        $status = $this->request->param('status');
        $keyword =input('keyword');
        // and
        if (!empty($keyword)) {
            // 公司名模糊 其他没必要
            $where['pc.zs_name|pc.company_name'] = array('like', '%' . $keyword . '%');
            // 公司名模糊 其他没必要
//            $where['pc.company_name'] = array('like', '%' . $keyword . '%');
        }

        //当前用户权限
        if($this->admin['is_super']){
            //不加限制条件
        }else{
            //查询当前用户角色
            //查看角色id
            $admin_role = model('admin_role')->where(['admin_id'=>$this->admin['id']])->find();
            $role = model('role')->where(['id'=>$admin_role['org_id']])->find();
            if($role['is_gl']==1){
                $org_ids = xj_zz_ids($this->admin['org_id']);
                //所有所属组织的用户 id
                $adminarr =  model('admin')->field('id')->where(['org_id'=>['in',$org_ids]])->select();
                $admin_ids = array_column($adminarr,'id');
                $where['f.member_id'] = array('in',$admin_ids);
            }else{
                $where['f.member_id'] = $this->admin['id'];
            }
        }
        if($status||$status==="0"){
            $where['f.status'] = array('in',$status);
        }
        if(!empty($this->request->param('project_id'))){
            $where['p.project_id'] = $this->request->param('project_id');
        }
        if(!empty($this->request->param('exhibition_id'))){
            $where['p.exhibition_id'] = $this->request->param('exhibition_id');
        }
        //查询可优化
        $list = Db::name('company_follow')
            ->alias('f')
            ->field('f.*,a.realname,pc.company_name,a.mobile,pc.zs_name')
            ->join('company_public p','f.public_id=p.id','left')
            ->join('admin a','f.member_id=a.id','left')
            ->join('company_public_company pc','f.public_id=pc.public_id','left')
            ->where($where)->order('f.id desc')
            ->limit(($page-1)*$pagesize.','.$pagesize)
            ->select();
        $data =array();
        foreach ($list as $k =>&$v){
//            //获取映射表公司信息
            $company_public_company =  db('company_public_company')->where(['c_id'=>$v['company_id'],'public_id'=>$v['public_id']])->find();
            //最近联络时间
            $where1['follow_id'] = $v['id'];
            $where1['public_id'] = $v['public_id'];
            $where1['member_id'] = $this->admin['id'];
            $FollowLog = model('FollowLog')->where($where1)->order('time desc')->find();
            //查询展位号数据
            $booth = model('Booth')->field('number')->where(['agent_id'=>$v['id']])->select();
            $v['booth'] = $booth;
            $v['followlog'] = $FollowLog;
            $v['exhibition'] = model('Exhibition')->findWhere(['id'=>$v['exhibition_id']]);
            $v['company_public_company'] = $company_public_company;
//            $booth_number = array_column($booth,'number');
//            $area = array_column($booth,'area');
//            $data[$k]['id'] = $v['id'];//序号
////            $data[$k]['zs_name'] = $company_public_company['zs_name'];//展商名称
//            $data[$k]['zs_name'] = empty($v['zs_name'])?$v['company_name']:$v['zs_name'];//展商名称
//            $data[$k]['zs_status'] = $v['status'];//展商状态
//            $data[$k]['zs_status_name'] = $this->status_name[$v['status']];//展商状态名字
//            $data[$k]['jbcz'] = 1;//基本操作
//            $data[$k]['ywy'] = $v['realname'];//业务员
//            $data[$k]['zw_number'] =  $booth_number;//展位号
//            $data[$k]['zw_type'] = '';//展位类别
//            $data[$k]['zw_area'] = $area;//展位面积
//            $data[$k]['zp_type'] = '';//展品类别
//            $data[$k]['source'] = $v['is_old'];//来源
//            $data[$k]['lb'] = '';//连报
//            $data[$k]['sale_jd'] = $v['status'];//销售进度
//            $data[$k]['time'] = date('Y-m-d H:i:s',$FollowLog['time']);//最后联络时间
//            $data[$k]['member_grade'] = '';//会员等级
//            $data[$k]['member_id'] = '';//会员编号
//            $data[$k]['zs_type'] = '';//展商类别
            unset($company_public_company);
            unset($FollowLog);
        }
        //如果不为空则返回指定列
        if(!empty($list_key)){
            $list_key = explode(',',input('list_key'));//需要返回的列
            $datas = [];
            foreach ($list_key as $value){
                $datas[] = array_column($data,$value,$value);
                if($value =='zs_status'){
                    $datas[] = array_column($data,'zs_status_name','zs_status_name');
                }
            }

        }else{
            $datas = $data;
        }
        unset($data);
        $total =  Db::name('company_follow')->alias('f')
            ->join('company_public p','f.public_id=p.id','left')
            ->join('company_public_company pc','f.public_id=pc.public_id','left')->where($where)->count();
//        //统计各个状态下的数量
        $status_count = $this->model->field("status,count('id') as sum")->where(['is_status'=>array('<>',-1)])->group('status')->select();
        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total,'page'=>$total,' pagesize'=>$pagesize]]);
    }

}